#include "head_s.h"

int cd(user_t* status, const portocol_t* portocol, int net_fd) {
    printf("The cmd : cd\n");
    printf("The arg : %s\n", status->arg);
    printf("The path: %s\n", status->path);
    int off = strlen(status->arg);
    printf("The arg len: %d\n", off);

    //拼接当前工作路径
    char the_path[1024] = {0};
    strcpy(the_path, status->base_path);
    strcat(the_path, status->user_name);
    strcat(the_path, status->path);
    
    printf("The 绝对路径1：%s\n", the_path);

    //cd移动当前工作路径

    //判断参数种类：
    //1.“..”则返回父目录
    //2.“.”不变
    //3.“\0”返回到用户家目录下
    //4.正常则移动到下一级目录status.arg上：向用户名后路径拼接arg
    //失败返回failed
    if(strcmp(status->arg ,"..") == 0){
        printf("arg is '..'\n");
        
        int len = strlen(status->arg);
        send(net_fd, &len, sizeof(int), MSG_NOSIGNAL);
        send(net_fd, status->arg, len, MSG_NOSIGNAL);

    }else if(strcmp(status->arg, ".") == 0) {
        printf("arg is '.'\n");
        
        int len = 1;
        send(net_fd, &len, sizeof(int), MSG_NOSIGNAL);
        send(net_fd, ".", len, MSG_NOSIGNAL);     

    }else if(portocol->arg_num == 2){
        printf("arg is NULL\n");

        int len = 4;
        send(net_fd, &len, sizeof(int), MSG_NOSIGNAL);
        send(net_fd, "NULL", len, MSG_NOSIGNAL);

    }else {
        printf("arg is right\n");

        //遍历目录项找到与参数名相同的目录名
        DIR *dir = opendir(the_path); 
        struct dirent* curr; 
        while((curr = readdir(dir)) != NULL ) {
            
            printf("arg = %s, d_name = %s\n", status->arg, curr->d_name);
            
            if(strcmp(status->arg, curr->d_name) == 0){
                int size = strlen(status->arg) ;
                send(net_fd, &size, sizeof(int), MSG_NOSIGNAL);
                send(net_fd, status->arg, size, MSG_NOSIGNAL);

                closedir(dir);
                return 0; 
            }
        }
        closedir(dir);
        int size = 6;
        send(net_fd, &size, sizeof(int), MSG_NOSIGNAL);
        send(net_fd, "failed", size, MSG_NOSIGNAL);
    }

    return 0;
}
